package cn.tedu.egweibo04.controller;

import cn.tedu.egweibo04.base.response.JsonResult;
import cn.tedu.egweibo04.base.response.StatusCode;
import cn.tedu.egweibo04.mapper.UserMapper;
import cn.tedu.egweibo04.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo04.pojo.dto.UserRegDTO;
import cn.tedu.egweibo04.pojo.entity.User;
import cn.tedu.egweibo04.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/user")
@Api(tags = "01.用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/reg")
    @ApiOperation("用户注册")
    @ApiImplicitParam(name = "userRegDTO", value = "用户注册数据", required = true, dataType = "UserRegDTO")
    public JsonResult register(@RequestBody UserRegDTO userRegDTO) {
        UserVO userVO = userMapper.selectUser(userRegDTO.getUsername());
        if (userVO != null) {
            return new JsonResult(StatusCode.USERNAME_OCCUPIED, userVO);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        return JsonResult.ok(userMapper.insertUser(user));
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    @ApiImplicitParam(name = "userLoginDTO", value = "用户登录数据", required = true, dataType = "UserLoginDTO")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session) {
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername());
        if (userVO == null) return new JsonResult(StatusCode.USERNAME_ERROR);
        if (userVO.getPassword().equals(userLoginDTO.getPassword())) {
            session.setAttribute("user", userVO);
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
    }

    @GetMapping("/currentUser")
    @ApiOperation("获取当前登录用户信息")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        return JsonResult.ok(userVO);
    }
@GetMapping("/logout")
@ApiOperation("用户注销")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }

}
